package com.bdqn.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bdqn.demo.dao.RoleDao;
import com.bdqn.demo.dao.UserRoleDao;
import com.bdqn.demo.pojo.Role;
import com.bdqn.demo.pojo.UserRole;
import com.bdqn.demo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 角色表(Role)表服务实现类
 *
 * @author makejava
 * @since 2024-01-16 19:08:22
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService {

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleDao roleDao;

    @Override
    public boolean allocate(Integer uid, Integer roleId) {
        LambdaQueryWrapper<UserRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserRole::getUserId, uid);
        userRoleDao.delete(lqw);
        return userRoleDao.insert(new UserRole(uid, roleId)) > 0;
    }

    @Override
    public List<Role> findAll() {
        LambdaQueryWrapper<Role> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Role::getStatus, 0);
        return list(lqw);
    }

    @Override
    public IPage<Role> getPage(Integer pageNo, Integer pageSize, String name) {
        IPage<Role> page = new Page<>(pageNo, pageSize);
        page.setTotal(roleDao.count(name));
        page.setPages((int) (Math.ceil(page.getTotal() / (double) pageSize)));
        List<Role> list = roleDao.getPage((pageNo - 1) * pageSize, pageSize, name);
        page.setRecords(list);
        return page;
    }
}

